using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using BrendanGrant.Helpers.FileAssociation;
using System.IO;

namespace dnFileEncryptor
{
	public partial class OptionsForm : Form
	{
		private static string SHELL_KEY_NAME = "dnFileEncryptor";
		private static string SHELL_MENU_TEXT = "Encrypt/Decrypt...";
		private static string SHELL_PROG_NAME = "EncryptedFile";
		
		public OptionsForm()
		{
			InitializeComponent();
		}

		private void changeState()
		{
			if (cbAssociateWithExtension.Checked)
				tbFileExtension.Enabled = true;
			else
				tbFileExtension.Enabled = false;
		}

		private bool isShellRegistered()
		{
			string regPath = string.Format(@"*\shell\{0}",
									   SHELL_KEY_NAME);

			return Registry.ClassesRoot.OpenSubKey(regPath) != null;
		}

		private void shellRegister()
		{
			string regPath = string.Format(@"*\shell\{0}", SHELL_KEY_NAME);

			// add context menu to the registry

			using (RegistryKey key =
				   Registry.ClassesRoot.CreateSubKey(regPath))
			{
				key.SetValue(null, SHELL_MENU_TEXT);
			}

			// add command that is invoked to the registry
			string menuCommand = string.Format("\"{0}\" \"%1\"",
								   Application.ExecutablePath);
			using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
				string.Format(@"{0}\command", regPath)))
			{
				key.SetValue(null, menuCommand);
			}
		}

		private void shellUnregister()
		{
			string regPath = string.Format(@"*\shell\{0}", SHELL_KEY_NAME);

			Registry.ClassesRoot.DeleteSubKeyTree(regPath);
		}

		private void fileAssociate(string extension)
		{
			if (extension != null && extension.Trim() != "")
			{
				FileAssociationInfo info = new FileAssociationInfo("." + extension);
				if (!info.Exists)
				{
					info.Create(SHELL_PROG_NAME);
				}
				ProgramAssociationInfo prog = new ProgramAssociationInfo(info.ProgID);
				if (!prog.Exists)
				{
					prog.Create("Open", new ProgramVerb("decrypt", Application.ExecutablePath + " %1"));
				}
				string iconPath = Path.GetDirectoryName(Application.ExecutablePath) + "\\Encryption-64.ico";
				prog.DefaultIcon = new ProgramIcon(iconPath);
			}
		}

		private void fileDisassociate(string extension)
		{
			if (extension != null && extension.Trim() != "")
			{
				FileAssociationInfo info = new FileAssociationInfo("." + extension);
				if (info.Exists)
				{
					ProgramAssociationInfo prog = new ProgramAssociationInfo(info.ProgID);
					if (prog.Exists)
					{
						for (int i = 0; i < prog.Verbs.Length; i++)
						{
							if (prog.Verbs[i].Name == "decrypt")
								prog.RemoveVerb(prog.Verbs[i]);
						}
					}
					prog.DefaultIcon = new ProgramIcon();
				}
			}
		}

		private void OptionsForm_Load(object sender, EventArgs e)
		{
			cbRegisterShell.Checked = isShellRegistered();
			cbAssociateWithExtension.Checked = Properties.Settings.Default.AssociateWithExtension;
			tbFileExtension.Text = Properties.Settings.Default.FileExtension;
			changeState();
		}
		
		private void cbRegisterShell_CheckedChanged(object sender, EventArgs e)
		{
			if (cbRegisterShell.Checked && !isShellRegistered())
			{
				shellRegister();
			}
			else if (!cbRegisterShell.Checked && isShellRegistered())
			{
				shellUnregister();
			}
		}
		
		private void OptionsForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			Properties.Settings.Default.AssociateWithExtension = cbAssociateWithExtension.Checked;
			if (cbAssociateWithExtension.Checked)
			{
				if (Properties.Settings.Default.FileExtension != tbFileExtension.Text)
				{
					fileDisassociate(Properties.Settings.Default.FileExtension);
					Properties.Settings.Default.FileExtension = tbFileExtension.Text;
					fileAssociate(Properties.Settings.Default.FileExtension);
				}
			}
			
			Properties.Settings.Default.Save();
		}

		private void formKeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
				Close();
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void cbAssociateWithExtension_CheckedChanged(object sender, EventArgs e)
		{
			changeState();
		}

		private void tbFileExtension_TextChanged(object sender, EventArgs e)
		{
			if (tbFileExtension.Text.Contains("."))
				tbFileExtension.Text = tbFileExtension.Text.Replace(".", "");
		}			
	}
}